package com.itheima.reggic.controller;

import com.itheima.reggic.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.UUID;

@Slf4j
@RestController
@RequestMapping("/common")
public class CommonController {

    @Value("${reggie.path}")
    private String basePath;

    @PostMapping("/upload")
    public R<String> upload(MultipartFile file) {
        log.info("文件上传，文件名:{}", file.getOriginalFilename());

        // 获取源文件名称
        String originalFilename = file.getOriginalFilename();
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        // 判断文件路径是否存在
        File dir = new File(basePath);
        if (dir.exists()) {
            // 目录不存在创建对应目录
            dir.mkdir();
        }
        // 生成文件名
        String fileName = UUID.randomUUID().toString();
        // 最终文件名
        String resFileName = fileName + suffix;
        try {
            file.transferTo(new File(basePath + resFileName));
        } catch (IOException e) {
            e.printStackTrace();
        }

        return R.success(resFileName);
    }

    @GetMapping("/download")
    public void download(String name, HttpServletResponse response) {
        log.info("获取文件，文件名称: {}", name);
        // 获取输入流
        try {
            FileInputStream fileInputStream = new FileInputStream(new File(basePath + name));


            ServletOutputStream outputStream = response.getOutputStream();
            int len = 0;
            byte[] bytes = new byte[1024];
            while ((len = fileInputStream.read(bytes)) != -1) {
                outputStream.write(bytes, 0, len);
                outputStream.flush();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
